package blockqueue;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者
 */
public class Producer implements Runnable {
	
	private volatile boolean isRunning = true; // 生产者线程是否在运行标志
	private BlockingQueue<String> queue; // 阻塞队列
	private static AtomicInteger count = new AtomicInteger(); // 自动更新的值
	
	public Producer(BlockingQueue<String> queue) {
		super();
		this.queue = queue;
	}

	@Override
	public void run() {
		System.out.println("启动生产者线程！");
		String data = null;
		Random r = new Random();
		
		try {
			while(isRunning) {
				System.out.println("正在生产数据...");
				Thread.sleep(r.nextInt(1000)); // 睡眠一个随机数时间，模拟处理业务
				data = "data:" + count.incrementAndGet(); // 以原子方式自增
				System.out.println("将数据：" + data + "放入队列...");
				if(!queue.offer(data, 2, TimeUnit.SECONDS)) {//设定的等待时间为2s，如果超过2s还没加进去返回true
					System.out.println("放入数据失败：" + data);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Thread.currentThread().interrupt();
		} finally {
			System.out.println("退出生产者线程！");
		}
	}

	public void stop() {
		isRunning = false;
	}
}
